<?php
class pdo_db {
    public $db;
    protected $stmt;
    protected $query_result;
    protected $row = array();
    protected $rowset = array();
    protected $num_queries = 0;
    protected $Sql = 0;
    public $chartset = "";
    protected $conn_id ="";
    public $transaction_opened = false;

    function pdo_db($sqlserver = "", $sqluser = "", $sqlpassword = "", $database = "", $persistency = true) {

       /* $this->persistency = $persistency;
        $this->user = $sqluser;
        $this->password = $sqlpassword;
        $this->server = $sqlserver;
        $this->dbname = $database;*/
        //$dsn = "mysql:host=" . $sqlserver . ";dbname=$database";
        //$cnx = new PDO("odbc:Driver={SQL Server};Server=127.0.0.1;Database=comm00;",'sa','123456'); 
        //$this->db = new PDO($dsn, $sqluser, $sqlpassword);
        //$dsn = "odbc:Driver={SQL Server};Server=" . $sqlserver . ";Database=$database";
        //$this->db = new PDO("dblib:host=$sqlserver;dbname=$database",$sqluser,$sqlpassword);
        //$this->db = new PDO($dsn, $sqluser, $sqlpassword);
        
        $this->db= new PDO( "sqlsrv:Server=".$sqlserver .";Database = ".$database, $sqluser, $sqlpassword);
        $this->db->lastInsertId();
        $this->db->setAttribute(PDO::ATTR_PERSISTENT , true);
        $this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        //$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        
        $this->conn_id="conn_".time();

       // echo "connection ".$this->conn_id." has been created <br>";
    }

    public function prepare($statement) {
        //echo "<br>".$statement."<br>";
        $res = $this->db->prepare($statement);
        $this->errorMessage();
        if ($res) {
            $this->stmt = $res;
            $this->Sql = $statement;
            return $this;
        }
       
    }

    public function beginTransaction() {
       $this->transaction_opened = true;
       //echo "<br/>=====Begin Transaction========<br/>";
       $this->db->beginTransaction();
       
       
    }

    public function commit() {
       //$this->db->commit(); 
      $this->transaction_opened = false;  
      // echo "<br/>=====Commit Transaction========<br/>";
       $this->db->commit();
    }

    public function rollBack() {
       $this->transaction_opened = false; 
       //echo "<br/>=====RollBack Transaction========<br/>";
       $this->db->rollBack();
       
       
       
    } 

    public function bindArray($params) {
        
        
       if (is_array($params)) {
            $keys = array_keys($params);
            for ($i = 0; $i < count($keys); $i++) {
                $key = $keys[$i];
                $value = $params[$key];
                //$value =mb_convert_encoding ($value,'utf-8','gb2312');
                $value = iconv('utf-8','gb2312',$value);
                $this->stmt->bindValue($key,$value);
            }
        }

       /* if (is_array($params)) {
            for ($i = 0; $i < count($params); $i++) {
                $value = $params[$i];
                //$this->stmt->bindValue(":" . $key, $params[$key], PDO::PARAM_NULL);
                $this->stmt->bindParam($i+1, $value );
            }


        }*/
        return $this;
    }

    public function execute($params=null) {
        try{
            if (is_array($params)) {
                 $keys = array_keys($params);
                for ($i = 0; $i < count($keys); $i++) {
                    //$value = $params[$i];
                    //$this->stmt->bindValue(":" . $key, $params[$key], PDO::PARAM_NULL);
                    //$this->stmt->bindParam($i+1, $value );
                    $key = $keys[$i];
                    $value = $params[$key];
                    //$value =mb_convert_encoding ($value,'utf-8','gb2312');
                   // $value = iconv('utf-8','gb2312',$value);
                    $this->stmt->bindValue($i+1,$value);
                }
                $this->stmt->execute();
            }

            $this->errorMessage();
        }
        catch(Exception $ex) {
            echo $ex->getMessage() . "</br>" . $ex->getTraceAsString();
        }
    }

    /*public function execute($params=null) {
        try{
            if ($this->stmt->execute($params)) {
                return true;
            }
            $this->errorMessage();
        }
        catch(Exception $ex) {
            echo $ex->getMessage() . "</br>" . $ex->getTraceAsString();
        }
    }*/

    public function fetchOne() {
        return $this->stmt->fetch();
    }

    public function fetch($sql) {
        $stmt = $this->db->query($sql);
        $stmt->execute();
        return $stmt->fetch();
    }

    public function query($sql) {
        $this->stmt = $this->db->query($sql);
        $this->stmt->execute();
        //$rows = iconv('GB2312','UTF-8',$rows);
        return $this->stmt->fetchAll();
    }

    public function columnCount() {

        return $this->stmt->columnCount();
    }

    public function getColumnMeta($i) {
        return $this->stmt->getColumnMeta($i);
    }

    public function getColumnMetas($tableName) {
        $this->executeSql("exec sp_columns ".$tableName);
        return $this->fetchAll();
    }

    public function fetchColumn($sql, $params = array()) {
        $this->prepare($sql);
        //$this->bindArray($params);
        //$this->stmt->execute($params);
        $this->execute($params);
        return $this->stmt->fetchColumn(0);
    }

    public function fetchAll() {

        $row = $this->stmt->fetchAll();
        
        $this->errorMessage();

        return $row;
    }

    public function exec($statement) {
        if ($this->db->exec($statement)) {
            $this->Sql = $statement;
            return $this->lastId();
        }
        $this->errorMessage();
    }
    public function executeSql($sql, $params = array()) {
        $this->prepare($sql);
        if (count($params) > 0) {
            //$this->bindArray($params);
            $this->stmt->execute($params);
        }
        else{
         $this->stmt->execute();   
        }
        
        $this->errorMessage();
    }

    public function affectRows() {
        return $this->stmt->rowCount();
    }

    public function errorMessage() {
        $msg = $this->db->errorInfo();
        if (count($msg) >= 3) {
           echo $msg[2];
        }
    }

    function sql_close() {
        $this->stmt = null;
        $this->db = null;
        //echo "<br/>==========closed==========<br/>";
    }

    function __destruct() {
        try{
            if($this->transaction_opened==true){
                $this->commit();
            }
            $this->sql_close();
            
        }catch (Exception $ex){
            echo $ex->getMessage();
        }

    }

} // if ... define

?>
